package com.example.myapplication.utils

import android.content.Context
import android.util.Log
import com.example.myapplication.DatabaseHelper
import com.example.myapplication.Patient
import com.example.myapplication.User
import com.example.myapplication.realtime.WebSocketManager
import kotlinx.coroutines.*
import org.json.JSONArray
import org.json.JSONObject

/**
 * 数据同步管理器 - 支持不同网络环境下的数据互通
 */
object DataSyncManager {
    
    private const val TAG = "DataSyncManager"
    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    /**
     * 同步所有数据到服务器
     */
    fun syncDataToServer(context: Context) {
        scope.launch {
            try {
                val databaseHelper = DatabaseHelper(context)
                val webSocketManager = WebSocketManager.getInstance(context)
                
                if (!webSocketManager.isConnected()) {
                    Log.w(TAG, "WebSocket未连接，无法同步数据")
                    return@launch
                }
                
                // 同步患者数据
                syncPatientsToServer(databaseHelper, webSocketManager)
                
                // 同步用户数据
                syncUsersToServer(databaseHelper, webSocketManager)
                
                Log.d(TAG, "数据同步到服务器完成")
            } catch (e: Exception) {
                Log.e(TAG, "同步数据到服务器失败", e)
            }
        }
    }
    
    /**
     * 从服务器获取数据
     */
    fun syncDataFromServer(context: Context) {
        scope.launch {
            try {
                val webSocketManager = WebSocketManager.getInstance(context)
                
                if (!webSocketManager.isConnected()) {
                    Log.w(TAG, "WebSocket未连接，无法获取数据")
                    return@launch
                }
                
                // 请求服务器数据
                requestServerData(webSocketManager)
                
                Log.d(TAG, "已请求服务器数据")
            } catch (e: Exception) {
                Log.e(TAG, "从服务器获取数据失败", e)
            }
        }
    }
    
    /**
     * 同步患者数据到服务器
     */
    private suspend fun syncPatientsToServer(
        databaseHelper: DatabaseHelper, 
        webSocketManager: WebSocketManager
    ) {
        withContext(Dispatchers.IO) {
            try {
                // 使用getAllPatients()方法获取所有患者数据
                val patients = databaseHelper.getAllPatients()
                val patientsJson = JSONArray()
                
                for (patient in patients) {
                    val patientJson = JSONObject().apply {
                        put("id", patient.id)
                        put("name", patient.name)
                        put("examinationDate", patient.examinationDate.time)
                        put("reporter", patient.reporter)
                        put("examinationName", patient.examinationName)
                        put("department", patient.department)
                        put("reportTime", patient.reportTime.time)
                        put("reportedBy", patient.reportedBy)
                        put("reportedByType", patient.reportedByType.name)
                    }
                    patientsJson.put(patientJson)
                }
                
                val syncMessage = WebSocketManager.RealtimeMessage(
                    type = WebSocketManager.MessageType.DATA_SYNC,
                    data = mapOf(
                        "type" to "patients",
                        "data" to patientsJson.toString()
                    )
                )
                
                webSocketManager.sendMessage(syncMessage)
                Log.d(TAG, "已同步${patients.size}条患者数据到服务器")
            } catch (e: Exception) {
                Log.e(TAG, "同步患者数据失败", e)
            }
        }
    }
    
    /**
     * 同步用户数据到服务器
     */
    private suspend fun syncUsersToServer(
        databaseHelper: DatabaseHelper, 
        webSocketManager: WebSocketManager
    ) {
        withContext(Dispatchers.IO) {
            try {
                val users = databaseHelper.getAllUsers()
                val usersJson = JSONArray()
                
                for (user in users) {
                    val userJson = JSONObject().apply {
                        put("id", user.id)
                        put("username", user.username)
                        put("realName", user.realName)
                        put("department", user.department)
                        put("userType", user.userType.name)
                        put("isApproved", user.isApproved)
                        put("isActive", user.isActive)
                        put("phone", user.phone)
                        // 注意：不同步密码
                    }
                    usersJson.put(userJson)
                }
                
                val syncMessage = WebSocketManager.RealtimeMessage(
                    type = WebSocketManager.MessageType.DATA_SYNC,
                    data = mapOf(
                        "type" to "users",
                        "data" to usersJson.toString()
                    )
                )
                
                webSocketManager.sendMessage(syncMessage)
                Log.d(TAG, "已同步${users.size}条用户数据到服务器")
            } catch (e: Exception) {
                Log.e(TAG, "同步用户数据失败", e)
            }
        }
    }
    
    /**
     * 请求服务器数据
     */
    private fun requestServerData(webSocketManager: WebSocketManager) {
        val requestMessage = WebSocketManager.RealtimeMessage(
            type = WebSocketManager.MessageType.DATA_SYNC,
            data = mapOf(
                "type" to "request",
                "request" to "all_data"
            )
        )
        webSocketManager.sendMessage(requestMessage)
    }
    
    /**
     * 处理从服务器接收的数据
     */
    fun handleServerData(context: Context, data: Map<String, Any>) {
        scope.launch {
            try {
                val databaseHelper = DatabaseHelper(context)
                val dataType = data["type"] as? String
                val jsonData = data["data"] as? String
                
                when (dataType) {
                    "patients" -> {
                        handlePatientsData(databaseHelper, jsonData)
                    }
                    "users" -> {
                        handleUsersData(databaseHelper, jsonData)
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "处理服务器数据失败", e)
            }
        }
    }
    
    /**
     * 处理患者数据
     */
    private suspend fun handlePatientsData(databaseHelper: DatabaseHelper, jsonData: String?) {
        if (jsonData == null) return
        
        withContext(Dispatchers.IO) {
            try {
                val patientsArray = JSONArray(jsonData)
                var syncCount = 0
                
                for (i in 0 until patientsArray.length()) {
                    val patientJson = patientsArray.getJSONObject(i)
                    
                    // 检查患者是否已存在
                    val existingPatient = databaseHelper.getPatientById(patientJson.getLong("id"))
                    if (existingPatient == null) {
                        // 患者不存在，插入新数据
                        val patient = Patient(
                            id = patientJson.getLong("id"),
                            name = patientJson.getString("name"),
                            examinationDate = java.util.Date(patientJson.getLong("examinationDate")),
                            reporter = patientJson.getString("reporter"),
                            examinationName = patientJson.getString("examinationName"),
                            department = patientJson.getString("department"),
                            reportTime = java.util.Date(patientJson.getLong("reportTime")),
                            reportedBy = patientJson.getLong("reportedBy"),
                            reportedByType = com.example.myapplication.UserType.valueOf(
                                patientJson.getString("reportedByType")
                            )
                        )
                        databaseHelper.addPatient(patient)
                        syncCount++
                    }
                }
                
                Log.d(TAG, "从服务器同步了${syncCount}条新患者数据")
            } catch (e: Exception) {
                Log.e(TAG, "处理患者数据失败", e)
            }
        }
    }
    
    /**
     * 处理用户数据
     */
    private suspend fun handleUsersData(databaseHelper: DatabaseHelper, jsonData: String?) {
        if (jsonData == null) return
        
        withContext(Dispatchers.IO) {
            try {
                val usersArray = JSONArray(jsonData)
                var syncCount = 0
                
                for (i in 0 until usersArray.length()) {
                    val userJson = usersArray.getJSONObject(i)
                    
                    // 检查用户是否已存在
                    val existingUser = databaseHelper.findUserByUsername(userJson.getString("username"))
                    if (existingUser == null) {
                        // 用户不存在，插入新数据
                        val user = User(
                            id = userJson.getLong("id"),
                            username = userJson.getString("username"),
                            password = "synced_user", // 同步的用户使用默认密码
                            realName = userJson.getString("realName"),
                            department = userJson.getString("department"),
                            userType = com.example.myapplication.UserType.valueOf(
                                userJson.getString("userType")
                            ),
                            isApproved = userJson.getBoolean("isApproved"),
                            isActive = userJson.getBoolean("isActive"),
                            phone = userJson.optString("phone", "")
                        )
                        databaseHelper.addUser(user)
                        syncCount++
                    }
                }
                
                Log.d(TAG, "从服务器同步了${syncCount}条新用户数据")
            } catch (e: Exception) {
                Log.e(TAG, "处理用户数据失败", e)
            }
        }
    }
    
    /**
     * 获取数据同步状态
     */
    fun getSyncStatus(context: Context): String {
        val webSocketManager = WebSocketManager.getInstance(context)
        val serverInfo = ServerConfig.getServerInfo(context)
        val isConnected = webSocketManager.isConnected()
        
        return """
            服务器配置: $serverInfo
            连接状态: ${if (isConnected) "已连接" else "未连接"}
            数据同步: ${if (isConnected) "可用" else "不可用"}
        """.trimIndent()
    }
    
    /**
     * 清理资源
     */
    fun destroy() {
        scope.cancel()
    }
} 